package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.dubbo.api.BlackListApi;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.SettingsApi;
import com.tanhua.model.domain.Question;
import com.tanhua.model.domain.Settings;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.Map;

/**
 * Created by Fausto on 2021/9/27 19:54
 */
@Service
public class SettingsService {

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private SettingsApi settingsApi;

    @DubboReference
    private BlackListApi blackListApi;

    @Autowired
    private SmsTemplate template;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询通用设置
     * @return
     */
    public SettingsVo settings() {
        SettingsVo vo = new SettingsVo();
        //1.获取用户id
        Long userId = UserHolder.getUserId();
        vo.setId(userId);
        //2.获取用户手机号码
        String mobile = UserHolder.getMobile();
        vo.setPhone(mobile);
        //3.获取用户的陌生人问题
        Question question=questionApi.findByUserId(userId);
        String txt=question== null? "你喜欢JAVA吗？":question.getTxt();
        vo.setStrangerQuestion(txt);
        //4.获取用户的App通知开关数据
        Settings settings=settingsApi.findByUserId(userId);
        if(settings != null){
        vo.setLikeNotification(settings.getLikeNotification());
        vo.setPinglunNotification(settings.getPinglunNotification());
        vo.setGonggaoNotification(settings.getGonggaoNotification());
        }
        return vo;
    }

    /**
     * 设置陌生人问题
     * @param content
     */
    public void saveQuestions(String content) {
        //1.获取当前用户id
        Long userId = UserHolder.getUserId();
        //2.调用api查询当前用户的陌生人问题
        Question question=questionApi.findByUserId(userId);
        //3.判断问题是否存在
        if (question==null){
        //3.1如果不存在，则保存
            question=new Question();
            question.setUserId(userId);
            question.setTxt(content);
            questionApi.save(question);
        }else {
        //3.2如果存在，则更新
            question.setTxt(content);
            questionApi.update(question);
        }
    }

    /**
     * 通知设置
     * @param map
     */
    public void saveSettings(Map map) {
        boolean likeNotification= (boolean) map.get("likeNotification");
        boolean pinglunNotification= (boolean) map.get("pinglunNotification");
        boolean gonggaoNotification= (boolean) map.get("gonggaoNotification");
        //1.获取当前用户id
        Long userId = UserHolder.getUserId();
        //2.根据用户id，查询用户通知设置
        Settings settings = settingsApi.findByUserId(userId);
        //3.判断
        if (settings==null){
            //保存
            settings=new Settings();
            settings.setUserId(userId);
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.save(settings);
        }else {
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.update(settings);
        }
    }

    /**
     * 分页查询黑名单列表
     * @param page
     * @param size
     * @return
     */
    public PageResult blacklist(int page, int size) {
        //1.获取当前用户的id
        Long userId = UserHolder.getUserId();
        //2.调用api查询用户的黑名单分页列表  Ipage对象
        IPage<UserInfo> iPage=blackListApi.findByUserId(userId,page,size);
        //3.对象转化，将查询的Ipage对象的内容封装到PageResult中
        PageResult pr=new PageResult(page,size,iPage.getTotal(),iPage.getRecords());
        //4.返回
        return pr;
    }

    /**
     * 取消黑名单设置
     * @param blackUserId
     */
    public void deleteBlackList(Long blackUserId) {
        //1.获取当前用户id
        Long userId = UserHolder.getUserId();
        //2.调用api删除
        blackListApi.delete(userId,blackUserId);
    }
    /**
     * 1.修改手机号：发送验证码
     */
    public void sendVerificationCode() {
        //1.获取当前用户手机号码
        String mobile = UserHolder.getMobile();
        //2.随机生成6位数字
        //String code = RandomStringUtils.randomNumeric(6);
        //为了方便测试设置成123456
        String code="123456";
        //3.调用template对象，发送短信
        template.sendSms(mobile, code);
        //4.将验证码存入到redis
        redisTemplate.opsForValue().set("CHECK_CODE_"+mobile, code, Duration.ofMinutes(5));
    }
    /**
     * 2.修改手机号：校验验证码
     */
    public Boolean checkVerificationCode(String code) {
        //1.获取当前用户手机号码
        String mobile = UserHolder.getMobile();
        //2、从redis中获取下发的验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + mobile);
        //3、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if(StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //验证码无效
            throw new BusinessException(ErrorResult.loginError());
        }
        //4、删除redis中的验证码
        redisTemplate.delete("CHECK_CODE_" + mobile);
        return true;
    }
    /**
     * 3.修改手机号：保存
     */
    public void saveNewMobile(String mobile) {
        //1.获取当前用户id
        Long userId = UserHolder.getUserId();
        //2.调用api根据用户id去修改当前手机号码
        settingsApi.saveNewMobile(userId,mobile);
    }
}
